package za.ac.wits.elen7045.scraper.providers.payfine;

import java.util.HashMap;
import java.util.List;

import za.ac.wits.elen7045.enums.DataKey;
import za.ac.wits.elen7045.persistence.Environment;
import za.ac.wits.elen7045.persistence.dao.DaoFactory;
import za.ac.wits.elen7045.persistence.dao.SqlAccountDAO;
import za.ac.wits.elen7045.persistence.dao.SqlServiceProviderDAO;
import za.ac.wits.elen7045.persistence.model.Account;
import za.ac.wits.elen7045.persistence.model.CreditCardProviderStatement;
import za.ac.wits.elen7045.persistence.model.ServiceProvider;
import za.ac.wits.elen7045.persistence.model.ServiceProviderName;
import za.ac.wits.elen7045.persistence.model.Statement;
import za.ac.wits.elen7045.scheduler.BaseScraperSchedulerRules;
import za.ac.wits.elen7045.scheduler.InterfaceScraperJob;
import za.ac.wits.elen7045.scraper.interfaces.BaseScraper;

public class ScraperJob implements InterfaceScraperJob {

	public ScraperJob() {
		
	}
	
	@Override
	public void execute() {
		SqlServiceProviderDAO serviceProviderDao =  DaoFactory.getServiceProviderDAO(Environment.TEST);
		ServiceProvider provider = serviceProviderDao.getServiceProvider(ServiceProviderName.TESTING);

		SqlAccountDAO accountDAO = DaoFactory.getSqlAccountDAO();
		List<Account> accounts = accountDAO.getAccounts(ServiceProviderName.PAY_FINE);
		
		BaseScraper scraper = new ScraperService(provider);
		BaseScraperSchedulerRules scraperSchedulerRules = new ScraperSchedulerRules();
		for (Account acc : accounts) {
			if (!scraperSchedulerRules.canScrape(acc))
				return;
			scraper.scrapeSite();
			try {
				// VALIDATE HERE
				if (!scraper.validateScrape()) {
					throw new Exception("Validation failed");
				}
				
				HashMap<DataKey, String> data = scraper.getMappedData();
				
				CreditCardProviderStatement cc = new CreditCardProviderStatement();
				cc.setCloseBalance(Integer.parseInt(data.get(DataKey.PAYMENT_TOTAL)));
				
				DaoFactory.getSqlStatementDAO().addAccountStatement(acc, cc);
				
				// PERSIST DATA HERE
				Statement statement = new CreditCardProviderStatement();
				statement.setAccountId(Integer.parseInt(data.get(DataKey.ACCOUNT_NO)));
	
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
}
